package com.smsc.headend.task.engine.handler.impl.deviceconfig;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.smsc.headend.common.enums.PaymentSwithPreToPostOptGroupEnum;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.enums.SubTaskStatus;
import com.smsc.headend.module.task.enums.TaskType;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * (业务实现)
 *
 * @author wjh
 * @date 2022/5/18 10:59.
 */
public class FrozenLoadProfileHandler implements TaskHandler {

    @Autowired
    FeignAssetManagementService assetManagementService;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData cosemData, String actionResult) throws UDISTaskHandlerException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        if (StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.SwitchMeterPaymentPreToPost.name())) {
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            Boolean taskEnd = isTaskLastAtomicTask(task, atomicTask);
            assetManagementService.updateStepStatusToPost(taskId,task.getTaskNo(), task.getMeterId(), PaymentSwithPreToPostOptGroupEnum.FROZEN_DAILY_BILLING_PROFILE.getOperationGroup().longValue(), SubTaskStatus.Success.getCode(), null, SystemClock.now() / 1000,
                    null, taskEnd);
        }
        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        if (StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.SwitchMeterPaymentPreToPost.name())) {
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            assetManagementService.updateStepStatusToPost(taskId,task.getTaskNo(), task.getMeterId(), PaymentSwithPreToPostOptGroupEnum.FROZEN_DAILY_BILLING_PROFILE.getOperationGroup().longValue(), SubTaskStatus.Failed.getCode(), null, SystemClock.now() / 1000,
                    String.format("handle %s fail, [%s]", OperationName.forId(atomicTask.getOperationId()).getName(), message), false);
        }
        return -1;
    }
}
